//
//  TGLSFuDaoQianDaoViewController.m
//  TuoGLaos
//
//  Created by 欧腾 on 2017/12/27.
//  Copyright © 2017年 outeng. All rights reserved.
//

#import "TGLSFuDaoQianDaoViewController.h"
#import "THLSFuDaoTableViewCell.h"
#import "PGDatePicker.h"
#import "DDQRCodeViewController.h"
#import <AVFoundation/AVFoundation.h>

@interface TGLSFuDaoQianDaoViewController ()<UITableViewDelegate,UITableViewDataSource,PGDatePickerDelegate>
@property(nonatomic,strong)NSMutableArray*studentSingArray;
@property(nonatomic,strong)NSMutableArray*studentSingArraySet; //数组应用数组
//加载第几页
@property(nonatomic,assign)NSInteger page;

@property(nonatomic,strong)TGLSKongView*backView;

@end

@implementation TGLSFuDaoQianDaoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"托管签到";
    
    //初始化
    [self createUI];
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:YES];
     self.navigationController.navigationBarHidden = NO;
    //请求数据
    if (kStringIsEmpty(UserToken)) {
        return;
    }
    NSDateFormatter *formater = [[ NSDateFormatter alloc] init];
    NSDate *curDate = [NSDate date];//获取当前日期
    [formater setDateFormat:@"yyyy-MM-dd"];//这里去掉 具体时间 保留日期
    NSString*curTime = [formater stringFromDate:curDate];
    self.todayDate.text = curTime;
     self.page = 1;
    //请求数据
    [self.studentSingArraySet removeAllObjects];
    [self downQianDaoList];
  
   
    
}
-(void)createUI{
    self.studentSingArray = [[NSMutableArray alloc] init];
    self.studentSingArraySet  = [[NSMutableArray alloc] init];
    self.tableViewHead.frame = CGRectMake(0, 64, kScreenWidth, 50);
    
    self.tableView.backgroundColor =UIColorHex(0xF4F2F3);
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.tableView registerNib:[UINib nibWithNibName:@"THLSFuDaoTableViewCell" bundle:nil] forCellReuseIdentifier:@"THLSFuDaoTableViewCell"];
    
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        self.page = 1;
        [self.studentSingArraySet removeAllObjects];
        [self downQianDaoList];
    }];
    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        self.page++;
        [self downQianDaoList];
    }];
    //选择日期
    [self.choiseDate addTarget:self action:@selector(choiseDateClick) forControlEvents:UIControlEventTouchUpInside];
    
    //二维码扫描
    [self.erWeiMaBtn addTarget:self action:@selector(saoMiaoClick) forControlEvents:UIControlEventTouchUpInside];
    self.backView= [[TGLSKongView alloc] initWithFrame:CGRectMake(kScreenWidth/2-60,kScreenHeight/2-60,120 , 120)];
    self.backView.hidden = YES;
    [self.view addSubview: self.backView];
}
#pragma mark 扫码
-(void)saoMiaoClick{
    if ([self validateCamera] && [self canUseCamera]) {
        
        [self showQRViewController];
        
    } else {
        
    }
}
-(BOOL)validateCamera {
    
    return [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera] &&
    [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceRear];
}
-(BOOL)canUseCamera {
    
    NSString *mediaType = AVMediaTypeVideo;
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:mediaType];
    if(authStatus == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied){
        
        NSLog(@"相机权限受限");
        
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"请在设备的设置-隐私-相机中允许访问相机。" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alertView show];
        return NO;
    }
    
    return YES;
}
- (void)showQRViewController {
    
    DDQRCodeViewController *vc = [[DDQRCodeViewController alloc] initWithScanCompleteHandler:^(NSString *url) {
        NSLog(@"%@",url);
        [[DDNetworkManagerDate makeUrlIndexmembehomework_sing_add:UserToken school_id:[USER_DEFAULT objectForKey:@"school_id"] login_id:[USER_DEFAULT objectForKey:@"login_id"] student_code:url] post_RequestFinshSuccess:^(id responseObject) {
            NSLog(@"%@",responseObject);

           
             [self.navigationController popViewControllerAnimated:YES];
            [self showCenterMessage:responseObject[@"msg"]];
            
        } failure:^(id errorObject) {
            
        }];
    }];
    
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark 日期选择
-(void)choiseDateClick{
    PGDatePicker *datePicker = [[PGDatePicker alloc]init];
    datePicker.delegate = self;
    [datePicker showWithShadeBackgroud];
    datePicker.datePickerType = PGDatePickerType2;
    datePicker.isHiddenMiddleText = false;
    datePicker.titleLabel.text = @"日期选择";
    datePicker.datePickerMode = PGDatePickerModeDate;
}
#pragma PGDatePickerDelegate
- (void)datePicker:(PGDatePicker *)datePicker didSelectDate:(NSDateComponents *)dateComponents {
    
    NSLog(@"dateComponents = %ld-%ld-%ld", (long)dateComponents.year,dateComponents.month,dateComponents.day);
    self.todayDate.text = [NSString stringWithFormat:@"%ld-%ld-%ld",dateComponents.year,dateComponents.month,dateComponents.day];
    self.page = 1;
    [self.studentSingArraySet removeAllObjects];
    [self downQianDaoList];
}
-(void)downQianDaoList{
    [[DDNetworkManagerDate makeUrlIndexmembehomework_sing_list:UserToken school_id: [USER_DEFAULT objectForKey:@"school_id"] login_id:[USER_DEFAULT objectForKey:@"login_id"] search_date:self.todayDate.text  num:@"" page:[NSString stringWithFormat:@"%ld",(long)self.page]] post_RequestFinshSuccess:^(id responseObject) {
        NSLog(@"%@",responseObject);
        NSNumber *code = [responseObject objectForKey:@"code"];
        if([code integerValue] == 100) {
            self.studentSingArray = (NSMutableArray *)[NSArray yy_modelArrayWithClass:[TGLSStudentList class] json:responseObject[@"list"]];
            for (int i = 0; i<self.studentSingArray.count; i++) {
                TGLSleave_listModel*model = self.studentSingArray[i];
                [self.studentSingArraySet addObject:model];
            }
        }
        if ([code integerValue] == 102) {
      
            [USER_DEFAULT setObject:@"" forKey:@"token"];
            [USER_DEFAULT synchronize];
            [XHToast showCenterWithText:responseObject[@"msg"]];
            TGLSLoginViewController*login = [[TGLSLoginViewController alloc]init];
            
            [self.navigationController pushViewController:login animated:YES];
        }
        if (self.studentSingArraySet.count == 0) {
            self.backView.hidden = NO;
           
            self.tableView.scrollEnabled = NO;
        }else{
            self.tableView.scrollEnabled = YES;
          
            self.backView.hidden = YES;
        }
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        [self.tableView reloadData];
    } failure:^(id errorObject) {
        
    }];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.studentSingArraySet.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 110;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    THLSFuDaoTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"THLSFuDaoTableViewCell" forIndexPath:indexPath];
    cell.contentView.backgroundColor = UIColorHex(0xF4F2F3);
    [cell configWithModel:self.studentSingArraySet[indexPath.row]];
    cell.selectionStyle = 0;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
   
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
